<?php
/**
 * @author JohnnyDen <413819942@qq.com>
 * @package addons\autocontentincome\controller
 * @copyright 2018年11月19日
 */
namespace addons\autocontentincome\controller;


use mip\AdminBase;
class ApiAdminACI extends AdminBase
{

    protected $notify_url   = 'aci_callback/record.html';
    
    public function autoContentIncomeDel()
    {
        $id = input('post.id');
        if (!$id) {
          return jsonError('缺少参数');
        }

        $autoContentIncome = db('AutoContentIncome')->where('id_org', config('orgId'))->where('id',$id)->find();
        if ($autoContentIncome) {
            db('AutoContentIncome')->where('id',$id)->delete();
            db('AutoContentIncomeDetail')->where('aid',$id)->delete();
            return jsonSuccess('删除成功');
        } else {
            return jsonError('规则不存在');
        }
    }

    public function autoContentIncomeSelect()
    {
        $this->checkTimeout();
        
		$orderBy = input('post.orderBy');
		$order = input('post.order');

		if(!$orderBy){
           $orderBy = '';
		}
		if(!$order){
            $order = '';
		}
		$autoContentIncomeList = db('AutoContentIncome a')->field('a.*,b.name')->join('articles_category b', 'b.id=a.cid')->where('a.id_org', config('orgId'))->order($orderBy, $order)->select();
		return jsonSuccess('',['autoContentIncomeList' => $autoContentIncomeList]);

    }
    
    public function autoContentIncomeStep1() {
        $url    = input('post.url');
        if (!$url) {
            return jsonError('缺少参数');
        }
        
        $url = $this->completeUrl($url);
        
        if (0 != db('AutoContentIncome')->where('id_org', config('orgId'))->where('url', $url)->count()) {
            return jsonError('已存在该链接的迁入规则，请更换迁入地址');
        }
        
        $res = $this->spider()->autoList($url);
        if ($res['status'] != 200) {
            return jsonError($res['info']);
        }
        
        $res['data']['url'] = $url;
        return jsonSuccess('', $res['data']);
    }
    
    public function autoContentIncomeStep3() {
        $url    = input('post.url');
        $title  = input('post.title');
        
        $res = $this->spider()->autoArticle($url, $title);
        if ($res['status'] != 200) {
            return jsonError($res['info']);
        }
        
        return jsonSuccess('', $res['data']);
    }
    
    public function autoContentIncomeStep4() {
        $need_exe   = input('post.need_exe');
        $cid    = input('post.cid');
        $url    = input('post.url');
        $auto_rule    = input('post.auto_rule/a');
        
        if (!$cid || !$url || !$auto_rule || !$auto_rule['list_links']) {
            return jsonError('缺少参数');
        }
        $url    = $this->completeUrl($url);
        
        if (0 != db('AutoContentIncome')->where('id_org', config('orgId'))->where('url', $url)->count()) {
            return jsonError('已存在该链接的迁入规则，请更换迁入地址');
        }
        
        $auto_rule['list_url_patterns'] = [];
        $auto_rule['page_url_patterns'] = [];
        
        $spider = $this->spider();
        foreach ($auto_rule['list_links'] as $groups) {
            $urls   = array();
            foreach ($groups as $_url) {
                $urls[] = $_url['url'];
            }
            
            $res    = $spider->buildUrlPattern($urls);
            if ($res['status'] == 200) {
                $auto_rule['list_url_patterns'][]   = $res['data']['pattern'];
//                 $tmp[] = array(
//                     $res['data']['pattern'],
//                     $urls,
//                 );
            }
        }
        foreach ($auto_rule['page_links'] as $groups) {
            $urls   = array();
            foreach ($groups as $_url) {
                $urls[] = $_url['url'];
            }
            $res    = $spider->buildUrlPattern($urls);
            if ($res['status'] == 200) {
                $auto_rule['page_url_patterns'][]   = $res['data']['pattern'];
            }
        }
        //echo json_encode($tmp);die;
        
        if (!$auto_rule['list_url_patterns']) {
            return jsonError('迁入内容规则创建失败');
        }
        
        $id = uuid();
        $res = db('AutoContentIncome')->insert(array(
            'id'    => $id,
            'id_org'=> config('orgId'),
            'cid'   => $cid,
            'url'   => $url,
            'exe_status'=> 'default',
        ));
        if (!$res) {
            return jsonError('规则创建失败');
        }
        
        db('AutoContentIncomeDetail')->insert(array(
            'aid'       => $id,
            'auto_rule' => json_encode($auto_rule),
        ));
        
        if (!$need_exe) {
            return jsonSuccess('创建成功');
        }
        
        $res = $spider->crawlArticles($url, $this->domain.$this->notify_url, array(
            'rules'         => array(
                'list_url_patterns' => $auto_rule['list_url_patterns'],
                'page_url_patterns' => $auto_rule['page_url_patterns'],
            ),
            'attach'        => $id,
        ));
        if ($res['status'] != 200) {
            file_put_contents(RUNTIME_PATH.'tmp.log', "\n".'但启动任务失败：'.json_encode($res), FILE_APPEND);
            return jsonError('创建成功，但启动内容迁入任务失败：'.$res['info']);
        }
        
        db('AutoContentIncome')->where('id', $id)->update(array(
            'exe_status'        => 'doing',
            'exe_count'         => 1,
            'exe_start_time'    => time(),
        ));
        
        return jsonSuccess('创建成功，并启动内容迁入任务');
    }
    
    public function autoContentIncomeExe() {
        $id     = input('id');
        if (!$id) {
            return jsonError('缺少参数');
        }
        $res    = db('AutoContentIncome')->where('id_org', config('orgId'))->where('id', $id)->find();
        if (!$res) {
            return jsonError('参数错误');
        }
        
        $detail = db('AutoContentIncomeDetail')->where('aid', $id)->find();
        $detail['auto_rule']  = json_decode($detail['auto_rule'], true);
        
        $spider = $this->spider();
        $res = $spider->crawlArticles($res['url'], $this->domain.$this->notify_url, array(
            'rules'         => array(
                'list_url_patterns' => $detail['auto_rule']['list_url_patterns'],
                'page_url_patterns' => $detail['auto_rule']['page_url_patterns'],
            ),
            'attach'        => $id,
        ));
        if ($res['status'] != 200) {
            file_put_contents(RUNTIME_PATH.'tmp.log', "\n".'启动任务失败：'.json_encode($res), FILE_APPEND);
            return jsonError('启动内容迁入任务失败：'.$res['info']);
        }
        
        db('AutoContentIncome')->where('id', $id)->update(array(
            'exe_status'    => 'doing',
            'exe_count'     => db()->raw('exe_count+1'),
            'exe_start_time'=> time(),
        ));
        
        return jsonSuccess('成功启动内容迁入任务');
    }
    
    /**
     * 5分钟内未执行视为超时
     */
    private function checkTimeout() {
        $now    = time();
        //1分钟内不重复执行
        $time   = \Think\Cache::get('aci_check_doing_time');
        if ($time && $now - $time < 60) {
            return false;
        }
        \Think\Cache::set('aci_check_doing_time', $now);
        
        $map    = array(
            'exe_status'        => 'doing',
            'exe_start_time'    => array(array('gt', 0), array('lt', $now - 300)),
        );
        if (0 == db('AutoContentIncome')->where($map)->count()) {
            return false;
        }
        
        return db('AutoContentIncome')->where($map)->update(array(
            'exe_status'        => 'timeout',
        ));
    }
    
    private function completeUrl($url) {
        if ($url[strlen($url) - 1] != '/') {
            $basename = basename($url);
            if (!strpos($basename, '.')) {
                $url    .= '/';
            }
        }
        
        return $url;
    }
    
    private function spider() {
        return new \XppOpenApi\Core\Spider(123, '123');
    }
    
    /**
     * @deprecated
     */
    private function formatAutoRuleLinks($links) {
        $new_links = array();
        foreach ($links as $groups) {
            $group_sort = array();
            $sort   = array();
            foreach ($groups as $url) {
                $url['degree']  = rand(92,96) / 100;
                $degree_urls[$url['degree'].''] = $url['url'];
                $sort[$url['degree'].''] ++;
            }
            krsort($sort);
            arsort($sort);
            reset($sort);
            
            $new_links[]   = $degree_urls[key($sort)];
        }
        
        return $new_links;
    }

}